package com.lenovo.hawk.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 *  数据源配置信息
 * @author Hsg
 */
@Configuration
@Slf4j
public class DruidConfig {

    /**
     * Default DataSource
     *
     * @return
     */
    @Bean(name = "druidMySQLDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.mysql")
    @ConditionalOnProperty(name = "master.type", havingValue = "mysql", matchIfMissing = true)
    public DataSource druidMySQLDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "druidOracleDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.oracle")
    @ConditionalOnProperty(name = "slave.type", havingValue = "oracle", matchIfMissing = true)
    public DataSource druidOracleDataSource() {
        return new DruidDataSource();
    }

    @Primary
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //配置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(druidMySQLDataSource());
        //配置多数据源
        Map<Object,Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("masterDataSource",druidMySQLDataSource());
        dataSourceMap.put("slaveDataSource",druidOracleDataSource());
        dynamicDataSource.setDataSources(dataSourceMap);
        return dynamicDataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        // 配置数据源，此处配置为关键配置，如果没有将 dynamicDataSource作为数据源则不能实现切换
        sessionFactory.setDataSource(dynamicDataSource());
        sessionFactory.setTypeAliasesPackage("com.lenovo.hawk.pojo");    // 扫描Model
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));    // 扫描映射文件
        return sessionFactory;

    }

    /**
     * 事务配置  使用事务时在方法头部添加@Transactional注解即可
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dynamicDataSource());
    }

}
